#!/usr/bin/env bash
#
# ivycp  by paul phillips  part of sbt-extras
# https://github.com/paulp/sbt-extras

set -o pipefail

die () { echo >&2 "Error: $@" && exit 1; }

ivyjar="$IVYJAR"
[[ -f "$ivyjar" ]] || ivyjar="$HOME/.ivy2/cache/org.apache.ivy/ivy/jars/ivy-2.3.0.jar"
[[ -f "$ivyjar" ]] || ivyjar="$(brew --prefix)/Cellar/ivy/2.3.0/libexec/ivy-2.3.0.jar"
[[ -f "$ivyjar" ]] || die "Can't find ivy.jar. Set IVYJAR to its path."

program="$(basename "$0")"

if [[ $# -eq 0 ]]; then
  cat <<EOM
Usage: $program [dependency dependency ...]

Resolves and downloads all specified dependencies and creates a
classpath out of the transitive closure. The dependency format is

  org%name%rev%conf

The elements can be separated with : or ; in addition to %.
Only organization and name are required, with the others
defaulting to rev=latest.release and conf=default. Examples
using this program to create a classpath on the fly:

  $program org.scalaz%scalaz-core_2.11 org.jboss.netty%netty
  java -jar \$($program org.eclipse.jetty%jetty-start) --list-config

EOM

  exit 0
fi

dir="$(mktemp -dt ivycp)"
build="$dir/build.xml"

dependencyLine () {
  local fmt='      <dependency org="%s" name="%s" rev="%s" conf="%s" />'"\n"
  IFS=" " read org name rev conf <<<"$@"
  printf "$fmt" $org $name "${rev:-latest.release}" "${conf:-default}"
}

dependencyLines () {
  for arg in "$@"; do ( IFS=":;% " && set -- $arg && dependencyLine "$@" ); done
}

genBuildXml () {
  cat <<EOM
<?xml version="1.0" encoding="UTF-8"?>
<project name="ivycp" default="build" xmlns:ivy="antlib:org.apache.ivy.ant">
  <taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpath="$ivyjar"/>
  <target name="build">
    <ivy:resolve type="bundle,jar" log="quiet">
$1
    </ivy:resolve>
    <ivy:retrieve symlink="true" log="quiet"/>
  </target>
</project>
EOM
}

genBuildXml "$(dependencyLines "$@")" > "$build"
ant -q -f "$build" >/dev/null 2>/dev/null
code="$?"

if (( code == 0 )); then
  set -- $(readlink "$dir/lib"/*)
  ( IFS=: && echo "$*" )
else
  echo >&2 "Dependency retrieval failed: exit code $?"
fi

exit "$code"
